package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.internal.$Gson$Types;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.WemediaConstants.WemediaConstants;
import com.heima.model.common.constants.message.NewsAutoScanConstants;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.constants.message.PublishArticleConstants;
import com.heima.model.common.dtos.PageRequestDTO;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.wemedia.pojos.WmUser;
import com.heima.model.media.dto.WmNewsDTO;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.NewsAuthDTO;
import com.heima.model.wemedia.dtos.WmNewsMaterial;
import com.heima.model.wemedia.dtos.WmNewsPageReqDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.vos.WmNewsVO;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.record.DVALRecord;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Value("${file.oss.web-site}")
    String website;

    @Autowired
    RabbitTemplate rabbitTemplate;
    @Override
    public ResponseResult findList(WmNewsPageReqDTO dto) {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(dto.getKeyword())) {
            wrapper.like(WmNews::getTitle, dto.getKeyword());
        }
        if (dto.getStatus() != null) {
            wrapper.eq(WmNews::getStatus, dto.getStatus());
        }
        if (dto.getBeginPubDate() != null && dto.getEndPubDate() != null) {
            wrapper.ge(WmNews::getPublishTime, dto.getBeginPubDate()).le(WmNews::getPublishTime, dto.getEndPubDate());
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        if (dto.getChannelId() != null) {
            wrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }
        wrapper.eq(WmNews::getUserId, user.getId());
        wrapper.orderByDesc(WmNews::getCreatedTime);
        Page<WmNews> page = new Page(dto.getPage(), dto.getSize());
        IPage<WmNews> wmNewsIPage = this.page(page, wrapper);
        PageResponseResult pageResponseResult = new PageResponseResult(dto.getPage(), dto.getSize(), wmNewsIPage.getTotal());
        pageResponseResult.setData(page.getRecords());
        pageResponseResult.setHost(website);
        return pageResponseResult;
    }

    @Transactional
    @Override
    public ResponseResult submitNews(WmNewsDTO dto) throws InvocationTargetException, IllegalAccessException {
        if (dto == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto,wmNews);
        if (dto.getType().equals(WemediaConstants.WM_NEWS_TYPE_AUTO)) {
            wmNews.setType(null);
        }
        if (!CollectionUtils.isEmpty(dto.getImages())){
            String images = imageListToStr(dto.getImages());
            wmNews.setImages(images);
        }

        wmNews.setUserId(user.getId());
        saveWmNews(wmNews);
        if (WemediaConstants.WM_NEWS_DRAFT_STATUS.equals(wmNews.getStatus())){
            return ResponseResult.okResult();
        }
        List<String> congtentImages=parseContentImages(dto.getContent());
        if (!CollectionUtils.isEmpty(congtentImages)){
            saveRelativeInfo(congtentImages,wmNews.getId(),WemediaConstants.WM_CONTENT_REFERENCE);
        }
        saveRelativeInfoForCover(dto,congtentImages,wmNews);
        rabbitTemplate.convertAndSend(NewsAutoScanConstants.WM_NEWS_AUTO_SCAN_QUEUE,wmNews.getId());
        log.info("成功发送 待审核消息 ==> 文章id:{}", wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult findWmNewsById(Integer id) {

            //1 参数检查
            if (id == null) {
                CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
            }
            //2 执行查询
            WmNews wmNews = getById(id);
            if (wmNews == null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
            }
            //3 返回结果
            ResponseResult result = ResponseResult.okResult(wmNews);
            result.setHost(website);
            return result;

    }

    @Override
    public ResponseResult delNews(Integer id) {
        if(id == null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }
        //2.获取数据
        WmNews wmNews = getById(id);
        if(wmNews == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        //3.判断当前文章的状态  status==9  enable == 1
        if(wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())
                && wmNews.getEnable().equals(WemediaConstants.WM_NEWS_UP)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        //4.去除素材与文章的关系
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        //5.删除文章
        removeById(wmNews.getId());
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult downOrUp(WmNewsDTO dto) {
        if (dto==null){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        Short enable = dto.getEnable();
        if (enable==null||!WemediaConstants.WM_NEWS_UP.equals(enable)&&!WemediaConstants.WM_NEWS_DOWN.equals(enable)){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        if (wmNews.getArticleId()!=null) {
            if(enable.equals(WemediaConstants.WM_NEWS_UP)){
                // 上架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_UP_ROUTE_KEY,wmNews.getArticleId());
            }else {
                // 下架消息
                rabbitTemplate.convertAndSend(NewsUpOrDownConstants.NEWS_UP_OR_DOWN_EXCHANGE,
                        NewsUpOrDownConstants.NEWS_DOWN_ROUTE_KEY,wmNews.getArticleId());
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
//    @Autowired
//    WmNewsMapper wmNewsMapper;
//    @Override
//    public ResponseResult findList(NewsAuthDTO dto) {
//        log.info("参数{}",dto);
//        if (dto==null){
//            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
//        }
//        dto.checkParam();
//        LambdaQueryWrapper<WmNews> wrapper = Wrappers.lambdaQuery();
//
//        Page page=new Page(dto.getPage(),dto.getSize());
//        if (dto.getTitle()!=null){
//            wrapper.like(WmNews::getTitle,dto.getTitle());
//        }
//        if (dto.getStatus()!=null){
//            wrapper.eq(WmNews::getStatus,dto.getStatus());
//        }
//
//        IPage result = this.page(page, wrapper);
//
//    return new PageResponseResult(dto.getPage(),dto.getSize(),page.getTotal(),result.getRecords());
//
//
//
//
//      }
@Autowired
WmNewsMapper wmNewsMapper;
    /**
     * 查询文章列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(NewsAuthDTO dto) {
        //1.检查参数
        dto.checkParam();
        //记录当前页
        int currentPage = dto.getPage();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        if(StringUtils.isNotBlank(dto.getTitle())){
            dto.setTitle("%"+dto.getTitle()+"%");
        }

        //2.分页查询
        List<WmNewsVO> wmNewsVoList = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        long count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        ResponseResult result = new PageResponseResult(currentPage, dto.getSize(), count, wmNewsVoList);
        result.setHost(website);
        return result;
    }

    /**
     * 查询文章详情
     * @param id
     * @return
     */
    @Autowired
    WmUserMapper wmUserMapper;
    @Override
    public ResponseResult findWmNewsVo(Integer id) {
        //1参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章信息
        WmNews wmNews = getById(id);
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3.查询作者
        WmUser wmUser = null;
        if(wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //4.封装vo信息返回
        WmNewsVO wmNewsVo = new WmNewsVO();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(website);
        return responseResult;
    }

    /**
     * 自媒体文章人工审核
     * @param status 2  审核失败  4 审核成功
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Short status, NewsAuthDTO dto) {
        //1.参数检查
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.查询文章
        WmNews wmNews = getById(dto.getId());
        if(wmNews == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        // 检查文章状态 不能为9  已发布
        if (wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章已发布");
        }
        //3.修改文章状态
        wmNews.setStatus(status);
        if(StringUtils.isNotBlank(dto.getMsg())){
            wmNews.setReason(dto.getMsg());
        }
        updateById(wmNews);

        // TODO 通知定时发布文章
        if (status.shortValue()==WmNews.Status.ADMIN_SUCCESS.getCode())
        {
           // 通知定时发布文章
            // 发布时间
            long publishTime = wmNews.getPublishTime().getTime();
            // 当前时间
            long nowTime = new Date().getTime();
            long remainTime = publishTime - nowTime;
            // 发布文章
            rabbitTemplate.convertAndSend(PublishArticleConstants.DELAY_DIRECT_EXCHANGE
                    , PublishArticleConstants.PUBLISH_ARTICLE_ROUTE_KEY
                    , wmNews.getId()
                    , (message)->{                              // 延时消息 必设置
                        message.getMessageProperties().setHeader("x-delay",remainTime<=0?0:remainTime);
                        return message;
                    }
            );
            log.info("立即发布文章通知成功发送，文章id : {}", wmNews.getId());
        }


        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveRelativeInfoForCover(WmNewsDTO dto, List<String> congtentImages, WmNews wmNews) {
        List<String> images=dto.getImages();
        if (WemediaConstants.WM_NEWS_TYPE_AUTO.equals(dto.getType())){
            if (congtentImages.isEmpty()){
                wmNews.setType(WemediaConstants.WM_NEWS_NONE_IMAGE);
            }else if (congtentImages.size()>0&&congtentImages.size()<=2){
               wmNews.setType(WemediaConstants.WM_NEWS_SINGLE_IMAGE);
                images=congtentImages.stream().limit(1).collect(Collectors.toList());
            }else {
                wmNews.setType(WemediaConstants.WM_NEWS_MANY_IMAGE);
                images=congtentImages.stream().limit(3).collect(Collectors.toList());
            }
            if (!CollectionUtils.isEmpty(images)){
                wmNews.setImages(imageListToStr(images));
            }
            updateById(wmNews);
        }
        if (!CollectionUtils.isEmpty(images)){
             images = images.stream().map(url -> url.replaceAll(website, "")).distinct().collect(Collectors.toList());
            saveRelativeInfo(images,wmNews.getId(),WemediaConstants.WM_IMAGE_REFERENCE);
        }
    }

    @Autowired
    WmMaterialMapper wmMaterialMapper;
    private void saveRelativeInfo(List<String> urls, Integer newsId, Short type) {
        List<Integer> ids = wmMaterialMapper.selectRelationsIds(urls, WmThreadLocalUtils.getUser().getId());
        if (CollectionUtils.isEmpty(ids)||ids.size()<urls.size()){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
       wmNewsMaterialMapper.saveRelations(ids,newsId,type);


        }




    private List<String> parseContentImages(String content) {
        List<Map> contentMap = JSONArray.parseArray(content, Map.class);
        return contentMap.stream().filter(map -> WemediaConstants.WM_NEWS_TYPE_IMAGE.equals(map.get("type")))
                .map(map -> (String) map.get("value"))
                .map(url -> url.replaceAll(website, ""))
                .distinct().collect(Collectors.toList());
    }

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;

    private void saveWmNews(WmNews wmNews) {
        wmNews.setCreatedTime(new Date());

        wmNews.setSubmitedTime(new Date());
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        if (wmNews.getId() == null) {
            save(wmNews);
        } else {
            LambdaQueryWrapper<WmNewsMaterial> wrapper = Wrappers.lambdaQuery();
            wmNewsMaterialMapper.delete(wrapper.eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            updateById(wmNews);

        }

    }

    private String imageListToStr(List<String> images) {
        return images.stream().map((url) -> url.replace(website, "")).collect(Collectors.joining(","));
    }

}
